<template>
  <view class="video-upload-component">
    <!-- 上传区域 -->
    <view 
      class="upload-area" 
      @click="chooseVideo"
      :class="{ disabled: uploading }"
    >
      <view class="upload-icon">
        <text>+</text>
      </view>
      <text class="upload-text">点击选择视频</text>
      <text class="upload-hint">或拖拽视频到此处</text>
    </view>
    
    <!-- 视频预览区域 -->
    <view v-if="videoTempPath" class="preview-container">
      <view class="video-preview">
          <video 
            :src="videoTempPath" 
            controls 
            class="preview-video"
            :show-center-play-btn="true"
          ></video>
          <view class="video-info">
            <text class="video-name">{{ videoName }}</text>
            <text class="video-size">{{ formatFileSize(videoSize) }}</text>
            <text class="video-duration">{{ formatDuration(videoDuration) }}</text>
          </view>
        
        <!-- 视频标题输入 -->
        <view class="input-group">
          <text class="input-label">视频标题 <text class="required">*</text></text>
          <input 
            class="input-field"
            v-model="videoTitle"
            placeholder="请输入视频标题（最多50字）"
            maxlength="50"
            :disabled="uploading"
          />
        </view>
        
        <!-- 视频描述输入 -->
        <view class="input-group">
          <text class="input-label">视频描述</text>
          <textarea 
            class="textarea-field"
            v-model="videoDescription"
            placeholder="请输入视频描述（选填，最多500字）"
            maxlength="500"
            rows="4"
            :disabled="uploading"
          />
        </view>
        
        <!-- 上传操作按钮 -->
        <view class="action-buttons">
          <button 
            class="btn-primary"
            @click="uploadVideo"
            :disabled="uploading"
          >
            {{ uploading ? '上传中...' : '开始上传' }}
          </button>
          <button 
            class="btn-secondary"
            @click="resetUpload"
            :disabled="uploading"
          >
            重新选择
          </button>
        </view>
        
        <!-- 上传进度 -->
        <view v-if="uploading" class="progress-container">
          <text class="progress-text">上传进度: {{ uploadProgress }}%</text>
          <view class="progress-bar">
            <view 
              class="progress-fill"
              :style="{ width: uploadProgress + '%' }"
            ></view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 上传成功提示 -->
    <view v-if="uploadSuccess" class="success-message">
      <text class="success-icon">✓</text>
      <text class="success-text">视频上传成功！</text>
    </view>
    
    <!-- 上传错误提示 -->
    <view v-if="uploadError" class="error-message">
      <text class="error-icon">✗</text>
      <text class="error-text">{{ uploadError }}</text>
    </view>
    
    <!-- 上传规则提示 -->
    <view class="upload-rules">
      <text class="rule-item">• 支持 MP4、MOV 等常见视频格式</text>
      <!-- <text class="rule-item">• 文件大小不超过 200MB</text> -->
      <!-- <text class="rule-item">• 视频时长不超过 60 秒</text> -->
    </view>

    <!-- 图片上传区域 -->
    <view class="image-upload-section">
      <view class="section-title">
        <text>上传封面图片</text>
      </view>
      
      <!-- 图片选择区域 -->
      <view 
        class="image-upload-area"
        @click="chooseImages"
        :class="{ disabled: imageUploading || uploading }"
      >
        <view class="image-upload-icon">
          <text>+</text>
        </view>
        <text class="image-upload-text">点击选择图片</text>
        <text class="image-upload-hint">支持JPG、PNG等格式</text>
      </view>
      
      <!-- 图片预览区域 -->
      <view v-if="imageList.length > 0" class="image-preview-grid">
        <view v-for="(image, index) in imageList" :key="index" class="image-item">
          <image :src="image.path" mode="aspectFill" class="preview-image"></image>
          <view class="image-overlay" @click="removeImage(index)">
            <text class="remove-icon">✕</text>
          </view>
          <text class="image-name">{{ image.name }}</text>
          <text class="image-size">{{ formatFileSize(image.size) }}</text>
        </view>
      </view>
      
      <!-- 图片上传按钮 -->
      <view v-if="imageList.length > 0" class="image-action-buttons">
        <button 
          class="image-btn-upload"
          @click="uploadImages"
          :disabled="imageUploading || uploading"
        >
          {{ imageUploading ? '图片上传中...' : '上传图片' }}
        </button>
        <button 
          class="image-btn-clear"
          @click="clearImages"
          :disabled="imageUploading || uploading"
        >
          清空图片
        </button>
      </view>
      
      <!-- 图片上传进度 -->
      <view v-if="imageUploading" class="image-progress-container">
        <text class="image-progress-text">图片上传进度: {{ imageUploadProgress }}%</text>
        <view class="image-progress-bar">
          <view 
            class="image-progress-fill"
            :style="{ width: imageUploadProgress + '%' }"
          ></view>
        </view>
      </view>
      
      <!-- 图片上传成功提示 -->
      <view v-if="imageUploadSuccess" class="image-success-message">
        <text class="image-success-icon">✓</text>
        <text class="image-success-text">图片上传成功！</text>
      </view>
      
      <!-- 图片上传错误提示 -->
      <view v-if="imageUploadError" class="image-error-message">
        <text class="image-error-icon">✗</text>
        <text class="image-error-text">{{ imageUploadError }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import { uploadVideoFile, uploadImageFile } from '@/utils/api.js';

export default {
  data() {
    return {
      videoTempPath: '',
      videoName: '',
      videoSize: 0,
      videoDuration: 0,
      videoTitle: '',
      videoDescription: '',
      uploading: false,
      uploadProgress: 0,
      uploadSuccess: false,
      uploadError: '',
      // 图片上传相关数据
      imageList: [],
      imageUploading: false,
      imageUploadProgress: 0,
      imageUploadSuccess: false,
      imageUploadError: ''
    }
  },
  methods: {
    // 选择视频（优先使用chooseMedia）
    async chooseVideo() {
      try {
        // 尝试使用现代化的chooseMedia API
        const res = await uni.chooseMedia({
          count: 1,
          mediaType: ['video'],
          sourceType: ['album', 'camera'],
          maxDuration: 60,
          camera: 'back'
        });
        
        if (res.tempFiles && res.tempFiles.length > 0) {
          const videoFile = res.tempFiles[0];
          this.handleVideoSelect(videoFile);
        }
      } catch (error) {
        // 降级到chooseVideo API
        this.fallbackChooseVideo();
      }
    },
    
    // 降级方案：使用chooseVideo API
    fallbackChooseVideo() {
      uni.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: 'back',
        success: (res) => {
          const videoFile = {
            tempFilePath: res.tempFilePath,
            size: res.size,
            duration: res.duration,
            name: this.getFileName(res.name)
          };
          this.handleVideoSelect(videoFile);
        },
        fail: (err) => {
          console.error('选择视频失败:', err);
          uni.showToast({
            title: '选择视频失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 处理选择的视频文件
    handleVideoSelect(videoFile) {
      this.videoTempPath = videoFile.tempFilePath || videoFile.path;
      this.videoName = videoFile.name || this.getFileName(this.videoTempPath);
      this.videoSize = videoFile.size || 0;
      this.videoDuration = videoFile.duration || 0;
      this.videoTitle = videoFile.name || this.getFileName(this.videoTempPath);
      // 重置上传状态
      this.uploadSuccess = false;
      this.uploadError = '';
      
      // 文件大小和时长限制检查已被注释，根据需求决定是否启用
      // if (this.videoSize > 200 * 1024 * 1024) {
      //   uni.showToast({
      //     title: '视频大小不能超过200MB',
      //     icon: 'none'
      //   });
      //   this.resetUpload();
      //   return;
      // }
      // 
      // if (this.videoDuration > 60) {
      //   uni.showToast({
      //     title: '视频时长不能超过60秒',
      //     icon: 'none'
      //   });
      //   this.resetUpload();
      //   return;
      // }
    },
    
    // 获取文件名
    getFileName(filePath) {
      const parts = filePath.split('/');
      return parts[parts.length - 1];
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    
    // 格式化视频时长
    formatDuration(seconds) {
      if (!seconds) return '00:00';
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },
    
    // 上传视频
    async uploadVideo() {
      // 检查视频标题是否为空
      if (!this.videoTitle.trim()) {
        uni.showToast({
          title: '请输入视频标题',
          icon: 'none'
        });
        return;
      }
      
      this.uploading = true;
      this.uploadProgress = 0;
      this.uploadSuccess = false;
      this.uploadError = '';
      
      try {
        // 调用上传API，并传入进度回调
        const result = await uploadVideoFile({
          videoPath: this.videoTempPath,
          fileName: this.videoName,
          videoTitle: this.videoTitle,
          videoDescription: this.videoDescription,
          // 添加进度回调函数
          onProgressUpdate: (progress) => {
            this.uploadProgress = progress;
          }
        });
        
        this.uploadProgress = 100;
        this.uploadSuccess = true;
        
        // 显示上传成功提示
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        });
        
        console.log('视频上传成功:', result);
        this.resetUpload();
      } catch (error) {
        this.uploadError = error.message || '上传失败，请重试';
        uni.showToast({
          title: this.uploadError,
          icon: 'none'
        });
      } finally {
        this.uploading = false;
      }
    },
    
    // 重置上传
    resetUpload() {
      this.videoTempPath = '';
      this.videoName = '';
      this.videoSize = 0;
      this.videoDuration = 0;
      this.videoTitle = '';
      this.videoDescription = '';
      this.uploading = false;
      this.uploadProgress = 0;
      this.uploadSuccess = false;
      this.uploadError = '';
    },
    
    // 选择图片 - 直接使用更广泛支持的chooseImage API
    chooseImages() {
      const remainingSlots = 9 - this.imageList.length;
      if (remainingSlots <= 0) {
        uni.showToast({
          title: '最多只能上传9张图片',
          icon: 'none'
        });
        return;
      }
      
      uni.chooseImage({
        count: remainingSlots, // 最多选择剩余的数量
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          if (res.tempFilePaths && res.tempFilePaths.length > 0) {
            // 处理选择的图片
            const newImages = res.tempFilePaths.map((path, index) => ({
              path: path,
              name: this.getFileName(path),
              size: res.tempFiles[index]?.size || 0
            }));
            
            this.imageList = [...this.imageList, ...newImages];
            
            // 重置上传状态
            this.imageUploadSuccess = false;
            this.imageUploadError = '';
          }
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 删除图片
    removeImage(index) {
      this.imageList.splice(index, 1);
      // 重置上传状态
      this.imageUploadSuccess = false;
      this.imageUploadError = '';
    },
    
    // 清空图片
    clearImages() {
      this.imageList = [];
      // 重置上传状态
      this.imageUploadSuccess = false;
      this.imageUploadError = '';
    },
    
    // 上传图片
    async uploadImages() {
      if (this.imageList.length === 0) {
        uni.showToast({
          title: '请先选择图片',
          icon: 'none'
        });
        return;
      }
      
      this.imageUploading = true;
      this.imageUploadProgress = 0;
      this.imageUploadSuccess = false;
      this.imageUploadError = '';
      
      try {
        // 循环上传每张图片
        for (let i = 0; i < this.imageList.length; i++) {
          const image = this.imageList[i];
          
          // 上传单张图片
          const result = await uploadImageFile({
            imagePath: image.path,
            imageTitle: this.videoTitle ? `${this.videoTitle} 封面${i + 1}` : `封面${i + 1}`,
            imageDescription: this.videoDescription || '',
            // 添加进度回调函数，计算整体进度
            onProgressUpdate: (progress) => {
              // 计算当前图片在整体上传中的进度贡献
              const progressPerImage = 100 / this.imageList.length;
              this.imageUploadProgress = Math.floor(i * progressPerImage + progress * progressPerImage / 100);
            }
          });
          
          console.log(`第${i + 1}张图片上传成功:`, result);
        }
        
        this.imageUploadProgress = 100;
        this.imageUploadSuccess = true;
        
        // 显示上传成功提示
        uni.showToast({
          title: `成功上传${this.imageList.length}张图片`,
          icon: 'success'
        });
        
      } catch (error) {
        this.imageUploadError = error.message || '图片上传失败，请重试';
        uni.showToast({
          title: this.imageUploadError,
          icon: 'none'
        });
      } finally {
        this.imageUploading = false;
      }
    }
  }
}
</script>

<style>
.video-upload-component {
  width: 100%;
}

/* 上传区域 */
.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2rpx dashed #dcdfe6;
  border-radius: 16rpx;
  padding: 60rpx 20rpx;
  background-color: #f5f7fa;
  transition: all 0.3s ease;
  cursor: pointer;
}

.upload-area:hover {
  border-color: #667eea;
  background-color: #edf2fc;
}

.upload-area.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.upload-icon {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #667eea;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.upload-icon text {
  font-size: 72rpx;
  line-height: 1;
  font-weight: 300;
}

.upload-text {
  font-size: 32rpx;
  color: #303133;
  margin-bottom: 10rpx;
}

.upload-hint {
  font-size: 24rpx;
  color: #909399;
}

/* 预览容器 */
.preview-container {
  margin-top: 40rpx;
}

.video-preview {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.preview-video {
  width: 100%;
  height: 400rpx;
  border-radius: 12rpx;
  background-color: #000;
}

.video-info {
  margin-top: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #ebeef5;
}

.video-name {
  font-size: 32rpx;
  color: #303133;
  display: block;
  margin-bottom: 8rpx;
}

.video-size,
.video-duration {
  font-size: 24rpx;
  color: #909399;
  margin-right: 20rpx;
}

/* 输入表单 */
.input-group {
  margin-top: 30rpx;
}

.input-label {
  display: block;
  font-size: 28rpx;
  color: #606266;
  margin-bottom: 12rpx;
}

.required {
  color: #f56c6c;
}

.input-field {
  width: 100%;
  height: 88rpx;
  background-color: #f5f7fa;
  border: 1rpx solid #dcdfe6;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #303133;
  box-sizing: border-box;
  transition: border-color 0.3s ease;
}

.input-field:focus {
  border-color: #667eea;
  outline: none;
}

.textarea-field {
  width: 100%;
  background-color: #f5f7fa;
  border: 1rpx solid #dcdfe6;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #303133;
  box-sizing: border-box;
  resize: none;
  transition: border-color 0.3s ease;
}

.textarea-field:focus {
  border-color: #667eea;
  outline: none;
}

/* 操作按钮 */
.action-buttons {
  margin-top: 40rpx;
  display: flex;
  gap: 20rpx;
}

.btn-primary {
  flex: 1;
  height: 96rpx;
  background-color: #667eea;
  color: white;
  border: none;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.btn-primary:hover {
  background-color: #5a67d8;
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.btn-primary:disabled {
  background-color: #c0c4cc;
  transform: none;
  box-shadow: none;
}

.btn-secondary {
  flex: 1;
  height: 96rpx;
  background-color: #f5f7fa;
  color: #606266;
  border: 1rpx solid #dcdfe6;
  border-radius: 12rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.btn-secondary:hover {
  color: #667eea;
  border-color: #667eea;
  background-color: #edf2fc;
}

.btn-secondary:disabled {
  color: #909399;
  border-color: #dcdfe6;
  background-color: #f5f7fa;
}

/* 进度条 */
.progress-container {
  margin-top: 30rpx;
}

.progress-text {
  display: block;
  font-size: 28rpx;
  color: #606266;
  margin-bottom: 12rpx;
}

.progress-bar {
  height: 12rpx;
  background-color: #e0e0e0;
  border-radius: 6rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  border-radius: 6rpx;
  transition: width 0.3s ease;
}

/* 消息提示 */
.success-message,
.error-message {
  margin-top: 30rpx;
  padding: 20rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
}

.success-message {
  background-color: #f0f9ff;
  border: 1rpx solid #bae7ff;
}

.error-message {
  background-color: #fef0f0;
  border: 1rpx solid #fbc4c4;
}

.success-icon,
.error-icon {
  font-size: 32rpx;
  margin-right: 10rpx;
}

.success-icon {
  color: #67c23a;
}

.error-icon {
  color: #f56c6c;
}

.success-text,
.error-text {
  font-size: 28rpx;
}

.success-text {
  color: #36cfc9;
}

.error-text {
  color: #f56c6c;
}

/* 上传规则 */
.upload-rules {
  margin-top: 30rpx;
  padding: 20rpx;
  background-color: #fafafa;
  border-radius: 8rpx;
}

.rule-item {
  display: block;
  font-size: 24rpx;
  color: #909399;
  margin-bottom: 8rpx;
}

.rule-item:last-child {
  margin-bottom: 0;
}

/* 图片上传区域样式 */
.image-upload-section {
  margin-top: 40rpx;
  padding-top: 30rpx;
  border-top: 1rpx solid #ebeef5;
}

.section-title {
  font-size: 32rpx;
  color: #303133;
  font-weight: bold;
  margin-bottom: 20rpx;
}

/* 图片选择区域 */
.image-upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2rpx dashed #dcdfe6;
  border-radius: 16rpx;
  padding: 40rpx 20rpx;
  background-color: #f5f7fa;
  transition: all 0.3s ease;
  cursor: pointer;
}

.image-upload-area:hover {
  border-color: #667eea;
  background-color: #edf2fc;
}

.image-upload-area.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.image-upload-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #667eea;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15rpx;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.image-upload-icon text {
  font-size: 48rpx;
  line-height: 1;
  font-weight: 300;
}

.image-upload-text {
  font-size: 28rpx;
  color: #303133;
  margin-bottom: 8rpx;
}

.image-upload-hint {
  font-size: 22rpx;
  color: #909399;
}

/* 图片预览网格 */
.image-preview-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  margin-top: 20rpx;
}

.image-item {
  position: relative;
  background-color: #fff;
  border-radius: 8rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.preview-image {
  width: 100%;
  height: 200rpx;
  background-color: #f5f7fa;
}

.image-overlay {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.remove-icon {
  color: white;
  font-size: 24rpx;
  font-weight: bold;
}

.image-name {
  display: block;
  font-size: 24rpx;
  color: #303133;
  padding: 8rpx 12rpx 0 12rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-size {
  display: block;
  font-size: 20rpx;
  color: #909399;
  padding: 0 12rpx 8rpx 12rpx;
}

/* 图片操作按钮 */
.image-action-buttons {
  margin-top: 20rpx;
  display: flex;
  gap: 20rpx;
}

.image-btn-upload {
  flex: 1;
  height: 80rpx;
  background-color: #667eea;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.image-btn-upload:hover {
  background-color: #5a67d8;
}

.image-btn-upload:disabled {
  background-color: #c0c4cc;
}

.image-btn-clear {
  flex: 1;
  height: 80rpx;
  background-color: #f5f7fa;
  color: #606266;
  border: 1rpx solid #dcdfe6;
  border-radius: 8rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.image-btn-clear:hover {
  color: #667eea;
  border-color: #667eea;
  background-color: #edf2fc;
}

.image-btn-clear:disabled {
  color: #909399;
  border-color: #dcdfe6;
  background-color: #f5f7fa;
}

/* 图片上传进度 */
.image-progress-container {
  margin-top: 20rpx;
}

.image-progress-text {
  display: block;
  font-size: 26rpx;
  color: #606266;
  margin-bottom: 10rpx;
}

.image-progress-bar {
  height: 10rpx;
  background-color: #e0e0e0;
  border-radius: 5rpx;
  overflow: hidden;
}

.image-progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #67c23a 0%, #5daf34 100%);
  border-radius: 5rpx;
  transition: width 0.3s ease;
}

/* 图片上传消息提示 */
.image-success-message,
.image-error-message {
  margin-top: 20rpx;
  padding: 16rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
}

.image-success-message {
  background-color: #f0f9ff;
  border: 1rpx solid #bae7ff;
}

.image-error-message {
  background-color: #fef0f0;
  border: 1rpx solid #fbc4c4;
}

.image-success-icon,
.image-error-icon {
  font-size: 28rpx;
  margin-right: 10rpx;
}

.image-success-icon {
  color: #67c23a;
}

.image-error-icon {
  color: #f56c6c;
}

.image-success-text,
.image-error-text {
  font-size: 26rpx;
}

.image-success-text {
  color: #36cfc9;
}

.image-error-text {
  color: #f56c6c;
}
</style>